// !#1 引入 React 核心包
import React, { Component } from 'react'
// !#2 负责渲染的包（虚拟 DOM 转真实 DOM 并渲染）
import ReactDOM from 'react-dom/client'
// 引入 CSS
import './index.css'
import avatar from './avatar.png'
import classNames from 'classnames'
import dayjs from 'dayjs'

class App extends Component {
  state = {
    // hot: 热度排序  time: 时间排序
    tabs: [
      {
        id: 1,
        name: '热度',
        type: 'hot',
      },
      {
        id: 2,
        name: '时间',
        type: 'time',
      },
    ],
    active: 'time', // 高亮的 type
    list: [
      {
        id: 1,
        author: '刘德华',
        comment: '给我一杯忘情水',
        time: '2021-11-10 09:09:00',
        img: 'https://y.qq.com/music/photo_new/T001R300x300M000003aQYLo2x8izP.jpg?max_age=2592000',
        // 1: 点赞 0：无态度 -1:踩
        attitude: 1,
      },
      {
        id: 2,
        author: '周杰伦',
        comment: '听妈妈的话',
        time: '2021-12-11 09:09:00',
        img: 'https://y.qq.com/music/photo_new/T001R500x500M0000025NhlN2yWrP4.jpg?max_age=2592000',
        // 1: 点赞 0：无态度 -1:踩
        attitude: 0,
      },
      {
        id: 3,
        author: '陈奕迅',
        comment: '十年',
        time: '2021-10-11 10:09:00',
        img: 'https://y.qq.com/music/photo_new/T001R500x500M000003Nz2So3XXYek.jpg?max_age=2592000',
        // 1: 点赞 0：无态度 -1:踩
        attitude: -1,
      },
    ],
    // !#1
    comment: '',
  }
  handleClick(active) {
    return () => {
      this.setState({ active })
    }
  }
  handleDel(index) {
    /* const idx = this.state.list.findIndex((item) => item.id === id)
    this.state.list.splice(idx, 1) */
    // 违背了数据的不可变性
    // this.state.list.splice(index, 1)
    // !一种方法是拷贝原数据，进行删除，把删除后的结果通过 setState 进行更新
    // !filter => 保留 => 返回的是一个新数组
    this.setState({
      list: this.state.list.filter((_, idx) => idx !== index),
    })
  }
  handleLike(id, attitude) {
    this.setState({
      list: this.state.list.map((item) => {
        if (item.id === id) {
          return {
            ...item,
            attitude,
          }
        } else {
          return item
        }
      }),
    })
  }
  renderList() {
    return this.state.list.length > 0 ? (
      this.state.list.map((item, index) => (
        <div className='list-item' key={item.id}>
          <div className='user-face'>
            <img className='user-head' src={item.img} alt='' />
          </div>
          <div className='comment'>
            <div className='user'>{item.author}</div>
            <p className='text'>{item.comment}</p>
            <div className='info'>
              <span className='time'>
                {dayjs(item.time).format('YYYY-MM-DD HH:mm:ss')}
              </span>
              <span
                className={classNames([
                  'like',
                  item.attitude === 1 ? 'liked' : '',
                ])}
                onClick={() =>
                  this.handleLike(item.id, item.attitude === 1 ? 0 : 1)
                }
              >
                <i className='icon'></i>
              </span>
              {/* hated 表示踩 */}
              <span
                className={`hate ${item.attitude === -1 ? 'hated' : ''}`}
                onClick={() =>
                  this.handleLike(item.id, item.attitude === -1 ? 0 : -1)
                }
              >
                <i className='icon'></i>
              </span>
              <span
                className='reply btn-hover'
                onClick={() => this.handleDel(index)}
              >
                删除
              </span>
            </div>
          </div>
        </div>
      ))
    ) : (
      <h2 style={{ textAlign: 'center' }}>暂无评论~~</h2>
    )
  }
  handleChangeInput = (e) => {
    this.setState({ comment: e.target.value })
  }
  handleSubmit = () => {
    if (this.state.comment.trim() === '') return alert('内容不能为空')
    // 把收集到 comment 加工成留言对象，添加到 list
    // !#5 把数据加工成评论对象并添加
    const o = {
      id: Date.now(), // uuid react-uuid
      author: '尼古拉斯',
      comment: this.state.comment,
      time: new Date(),
      img: avatar,
      // 1: 点赞 0：无态度 -1:踩
      attitude: 0,
    }
    // this.state.list.push(o)
    this.setState({ list: [o, ...this.state.list], comment: '' })
  }
  render() {
    const { state } = this
    return (
      <div className='App'>
        <div className='comment-container'>
          <div className='comment-head'>
            <span>{state.list.length} 评论</span>
          </div>
          <div className='tabs-order'>
            <ul className='sort-container'>
              {state.tabs.map((item) => (
                <li
                  key={item.id}
                  className={classNames({
                    on: item.type === state.active,
                  })}
                  onClick={this.handleClick(item.type)}
                >
                  按{item.name}排序
                </li>
              ))}
            </ul>
          </div>
          <div className='comment-send'>
            <div className='user-face'>
              <img className='user-head' src={avatar} alt='' />
            </div>
            <div className='textarea-container'>
              {/* //!#2 用状态 comment 和 textarea 进行绑定 */}
              {/* //!#3 监听 onChange 事件 */}
              <textarea
                cols='80'
                rows='5'
                placeholder='发条友善的评论'
                className='ipt-txt'
                value={state.comment}
                onChange={this.handleChangeInput}
              ></textarea>
              {/* //!#4 绑定点击事件 */}
              <button className='comment-submit' onClick={this.handleSubmit}>
                发表评论
              </button>
            </div>
            <div className='comment-emoji'>
              <i className='face'></i>
              <span className='text'>表情</span>
            </div>
          </div>
          <div className='comment-list'>{this.renderList()}</div>
        </div>
      </div>
    )
  }
}

ReactDOM.createRoot(document.querySelector('#root')).render(<App />)
